package concurrent.read;

import eventHandle.ServiceHandle;
import http.Request;
import radio.ServerListener;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zzf on 2017/4/26.
 */
public class Reader implements Callable<Request> {

    private static final String THREAD_NAME = "reader-thread-";
    private static AtomicInteger number = new AtomicInteger(0);

    private SelectionKey key;

    private ServerListener serverListener = new ServiceHandle();

    private SocketChannel channel;

    public Reader(SelectionKey key) {
//        super(THREAD_NAME+number.incrementAndGet());
        this.key = key;
        channel = (SocketChannel) key.channel();
    }


    @Override
    public Request call() throws Exception {
        try {
            Thread.currentThread().setName(THREAD_NAME+number.incrementAndGet());

            ByteBuffer buffer = ByteBuffer.allocate(1024);

            Request request = new Request(channel);

            System.out.println(Thread.currentThread()+"开始读------");
            channel.read(buffer);

            request.setInputData(buffer.array());
            serverListener.onRead(request);
            System.out.println("读完了-------");



            return request;


        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
